﻿using Common.Communal;
using ERP.Domain.Processs;
using ERP.Domain.Workorders;
using MediatR;
using Sell.Api.Read.Application.Command.WorkordersCommand;
using Sell.DTO;
using SqlSugar;

namespace Sell.Api.Read.Application.CommandHandlers.WorkordersCommandHandlers
{
    public class WorkorderslistCommandHandlers : IRequestHandler<WorkorderslistCommand, ApiResult<ApiPaging<workorderdto>>>
    {
        public ISqlSugarClient SqlSugar { get; }
        public WorkorderslistCommandHandlers(ISqlSugarClient sqlSugar)
        {
            SqlSugar = sqlSugar;
        }
        /// <summary>
        /// 生产工单列表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult<ApiPaging<workorderdto>>> Handle(WorkorderslistCommand request, CancellationToken cancellationToken)
        {
            ApiResult<ApiPaging<workorderdto>> res = new ApiResult<ApiPaging<workorderdto>>();
            res.Code = EnumCode.Ok;
            res.Message = " 工单列表显示成功";
            /// 初始化查询：关联 Workorder表和ProcessFlow表
            var query = SqlSugar.Queryable<Workorder>()
                .LeftJoin<ProcessFlow>((w,f) => w.ProcessflowId== f.Id)
                .Where(w => w.IsDelete == false).Select(
                (w, f) => new workorderdto
                {
                   ProcessflowId=w.ProcessflowId,
                    IsDelete=w.IsDelete,
                    Object=w.Object,
                     ProcessflowCode=f.ProcessflowCode,
                      ProcessflowName=f.ProcessflowName,
                        ProcessId=f.ProcessId,
                         progress=w.progress,
                        WorkorderCode=w.WorkorderCode,
                         Id=w.Id,
                          WorkorderName=w.WorkorderName,
                           WorkorderState=w.WorkorderState,
                });
            //SqlSugar分页查询实现
            ApiPaging<workorderdto> result = new ApiPaging<workorderdto>();
            result.TotalCount = query.Count();//查询总记录数
            result.TotalPage = (int)Math.Ceiling(result.TotalCount * 1.0 / request.pagesize);//计算总页数
            result.Data = query.Skip((request.pageindex - 1) * request.pagesize)//跳过前面的记录
                .Take(request.pagesize)//取指定页大小的记录
                .ToList();//执行查询并转为List
            res.Success(result, "查询成功");
            return res;
        }
    }
}
